package pl.lodz.p.browarex.mvc;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.inject.Inject;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import pl.lodz.p.browarex.model.Product;
import pl.lodz.p.browarex.services.interfaces.IProductService;

@Controller
public class AdminIndexController {

	@Inject
	IProductService productService;

	@RequestMapping("adminIndex")
	public String showPage(Model model) throws Exception {

		model.addAttribute("product", new Product());
		model.addAttribute("uploadItem", new UploadItem());
		model.addAttribute("productsList", productService.list());

		return "adminIndex";
	}

	@RequestMapping(value = "/getImage", method = RequestMethod.GET)
	public void getImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Long imageId = Long.parseLong(request.getParameter("imageId"));
		byte[] imageData = null;
		if (productService.load(imageId) != null) {
			imageData = productService.load(imageId).getImage();
		}
		if (imageData == null) {
			String realPath = request.getSession().getServletContext()
					.getRealPath("/img/noImage.jpg");
			InputStream is = new FileInputStream(realPath);
			imageData = IOUtils.toByteArray(is);
		}
		response.reset();
		response.setContentType("image/jpg");
		response.getOutputStream().write(imageData);
		response.getOutputStream().flush();
		response.getOutputStream().close();

	}

	@RequestMapping(value = "/deletePhoto", method = RequestMethod.POST)
	public String deletePhoto(Product product, BindingResult result, Model model) {
		product = productService.load(product.getId());
		product.setImage(null);
		productService.save(product);
		model.addAttribute("product", new Product());
		model.addAttribute("uploadItem", new UploadItem());
		model.addAttribute("productsList", productService.list());

		return "adminIndex";
	}

	@RequestMapping(value = "/photo", method = RequestMethod.POST)
	public String addEditPhoto(UploadItem uploadItem, BindingResult result,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, Model model) {

		Product product = productService.load(uploadItem.getId());
		model.addAttribute("productsList", productService.list());
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error: " + error.getCode() + " - "
						+ error.getDefaultMessage());
			}
			return "adminIndex";
		}
		try {
			MultipartFile file = uploadItem.getFileData();
			InputStream inputStream = null;
			if (file.getSize() > 0) {
				inputStream = file.getInputStream();
				product.setImage(IOUtils.toByteArray(inputStream));
				productService.save(product);
				inputStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("product", new Product());
		model.addAttribute("uploadItem", new UploadItem());
		model.addAttribute("productsList", productService.list());
		return "adminIndex";
	}

	private String uploadFolderPath;
	ServletConfig config;

	public String getUploadFolderPath() {
		return uploadFolderPath;
	}

	public void setUploadFolderPath(String uploadFolderPath) {
		this.uploadFolderPath = uploadFolderPath;
	}

}
